package com.acmedcare.framework.exchange.center.core.storage;

import com.acmedcare.framework.exchange.center.entity.bean.StageConfig;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

@Component
public class StageRepository {

  private final JdbcTemplate jdbcTemplate;

  public StageRepository(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }


  public List<StageConfig> getConfigs() {

    try {
      List<StageConfig> stageConfigs = jdbcTemplate
          .query("SELECT * FROM center_stage_config",
              new
                  StageConfigMapper());

      return stageConfigs;
    } catch (EmptyResultDataAccessException e) {

      return null;
    }
  }

  public void delete(Long id) {

    jdbcTemplate.update("DELETE FROM center_stage_config WHERE config_id=?", new Object[]{id});
  }

  public void insert(StageConfig stageConfig) {

    jdbcTemplate.update(
        "INSERT INTO center_stage_config (config_id,config_name,config_value,stage_name,config_update_time) VALUES(?,?,?,?,?)"
        , new Object[]{stageConfig.getConfigId(), stageConfig.getConfigName(),
            stageConfig.getConfigValue(), stageConfig.getStageName(),
            stageConfig.getConfigUpdateTime()});
  }

  class StageConfigMapper implements RowMapper<StageConfig> {

    @Override
    public StageConfig mapRow(ResultSet resultSet, int i) throws SQLException {
      StageConfig stageConfig = new StageConfig();
      stageConfig.setStageName(resultSet.getString("stage_name"));
      stageConfig.setConfigId(resultSet.getLong("config_id"));
      stageConfig.setConfigName(resultSet.getString("config_name"));
      stageConfig.setConfigValue(resultSet.getString("config_value"));
      stageConfig.setConfigUpdateTime(resultSet.getTime("config_update_time"));
      return stageConfig;
    }
  }
}
